<template>
  <div class="oe-review-teacher" v-loading="loading">
    <top-tip v-if="!stepMode && batchTitle" :examTitle="examTitle" :batchTitle="batchTitle" :goManage="true" :batchid="batchid"></top-tip>
    <div class="oe-manage-content">
      <div class="oe-manage-content__search">
        <span class="oe-search-label">姓名/工号：</span>
        <span class="oe-search-input">
          <a-input v-model="searchName" placeholder="请输入姓名/工号"></a-input>
        </span>
        <a-button type="primary" @click="searchTeacherForType()">查询</a-button>
        <a-button
          type="primary"
          @click="getAddTeacherListForType()"
          v-if="operationList.includes('add/edit/del:monitor')"
        >导入监考教师</a-button>
        <a-button
          type="primary"
          @click="distributionStu()"
          v-if="operationList.includes('add/edit/del:monitor')"
        >一键分配考生</a-button>
        <a-button
          class="oe-btn-delete"
          @click="deleteBatchTeacherForType()"
          v-if="operationList.includes('add/edit/del:monitor')"
        >批量删除</a-button>
      </div>
      <div class="oe-manage-content__table">
        <a-table
          :columns="columns"
          :dataSource="dataList"
          :rowSelection="tableSelection"
          :pagination="tablePagination"
          @change="onTableChange"
        >
          <span slot="operation" slot-scope="text, record">
            <a-tooltip placement="bottom" v-if="operationList.includes('add/edit/del:monitor')">
              <template slot="title">
                <span>删除</span>
              </template>
              <span
                class="oe-table-delete iconfont icon-delete"
                @click.stop="deleteTeacherForType(record.Id)"
              ></span>
            </a-tooltip>
            <a-tooltip placement="bottom" v-if="operationList.includes('add/edit/del:monitor')">
              <template slot="title">
                <span>分配监考学生</span>
              </template>
              <span class="oe-table-delete iconfont icon-jinru" @click.stop="clickAction(record)"></span>
            </a-tooltip>
          </span>
        </a-table>
      </div>
    </div>
    <a-modal
      title="一键分配考生"
      class="oe-student"
      :visible="cancelPublish"
      width="500px"
      :closable="false"
    >
      <div class="oe-select">
        <span class="oe-manage-select">
          <h3>温馨提示：</h3>
          <div>1、一键分配考生会将所有的考生进行随机分配</div>
          <div>2、每个监考教师监考的学生数量基本一致（因为存在除不尽的可能）</div>
          <div>3、一键分配会默认选择该考试下的所以监考教师进行分配</div>
        </span>
      </div>
      <template slot="footer">
        <a-button type="primary" @click="distribution(0)" style="margin-top: 16px">分配正式卷考生</a-button>
        <a-button type="primary" @click="distribution(1)" style="margin-top: 16px">分配补考卷考生</a-button>
        <a-button @click.stop="cancelPublish = false">取消</a-button>
      </template>
    </a-modal>
    <a-modal
      title="分配考生试卷类型"
      class="oe-select-block"
      :visible="choice"
      @cancel="choice = false"
      :footer="null"
    >
      <span class="oe-block-btn" @click="choicePaper(0)">正式卷</span>
      <span class="oe-block-btn" @click="choicePaper(1)">补考卷</span>
    </a-modal>
    <!-- 导入监考教师 -->
    <a-modal
      title="导入监考教师"
      class="oe-student"
      :visible="importTeacherModal"
      width="70%"
      @cancel="importedCancel"
    >
      <div class="oe-select">
        <span class="oe-select-input">
          <a-input placeholder="请输入教师名称或工号" v-model="searchName" />
        </span>
        <a-button type="primary" @click.stop="getAddProctorTeacherList()">查询</a-button>
      </div>
      <div class="oe-select-table">
        <a-table
          :columns="importedColumns"
          :dataSource="importDataList"
          :scroll="{ y: 240 }"
          :rowSelection="modalSelection"
          :pagination="modalPagination"
          @change="onModalChange"
        ></a-table>
      </div>
      <template slot="footer">
        <a-button @click="addProctorTeacher()" type="primary" html-type="submit">确定</a-button>
        <a-button @click.stop="importedCancel">取消</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import topTip from '@/components/top-tip/index.vue';
import GetOperationList from '@/lib/mixin/methods.js';
export default {
  mixins: [GetOperationList],
  name: 'proctorTeacher',
  components: {
    topTip
  },
  data() {
    return {
      loading: false,
      // table分页配置
      tablePagination: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.tablePagination.current = current;
          this.tablePagination.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          this.tablePagination.current = current;
          this.tablePagination.pageSize = pageSize;
        },
        buildOptionText(props) {
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0
      },
      // modal弹窗分页配置
      modalPagination: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.modalPagination.current = current;
          this.modalPagination.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          this.modalPagination.current = current;
          this.modalPagination.pageSize = pageSize;
        },
        buildOptionText(props) {
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0
      },
      // 表标题
      columns: [
        {
          title: '序号',
          dataIndex: 'number',
          width: '10%',
          key: 'number'
        },
        {
          title: '姓名',
          dataIndex: 'DisplayName',
          width: '15%',
          key: 'DisplayName'
        },
        {
          title: '工号',
          dataIndex: 'UserNo',
          width: '10%',
          key: 'UserNo'
        },
        {
          title: '用户名',
          dataIndex: 'UserName',
          width: '10%',
          key: 'UserName'
        },
        {
          title: '手机号',
          dataIndex: 'Mobile',
          width: '10%',
          key: 'Mobile'
        },
        {
          title: '院校',
          dataIndex: 'SchoolName',
          width: '15%',
          key: 'SchoolName'
        },
        {
          title: '正式监考人数',
          dataIndex: 'MonitorStuCount',
          width: '10%',
          key: 'MonitorStuCount'
        },
        {
          title: '补考监考人数',
          dataIndex: 'RepairMonitorStuCount',
          width: '10%',
          key: 'RepairMonitorStuCount'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '10%',
          key: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      // 数据列表
      dataList: [],
      visible: false,
      // 点击的用户
      teacherInfo: {},
      // 选择的值
      selectValue: [],
      //搜索
      searchName: '',
      cancelPublish: false,
      //导入教师
      importedColumns: [
        {
          title: '序号',
          dataIndex: 'number',
          align: 'center'
        },
        {
          title: '教师名称',
          dataIndex: 'DisplayName',
          sorter: true,
          align: 'center'
        },
        {
          title: '教师工号',
          dataIndex: 'UserNo',
          sorter: true,
          align: 'center'
        },
        {
          title: '所属院校',
          dataIndex: 'SchoolName',
          sorter: true,
          align: 'center'
        }
      ],
      importDataList: [],
      selectedRowKeys: [],
      importTeacherModal: false,
      getType: 0,
      modalDefaultKey: [],
      tableDefaultKey: [],
      // 操作List
      operationList: [],
      IsOpList: [],
      manyVisible: false,
      selectModalValue: [],
      choice: false,
      choiceTeaId: '',
      batchTitle: '',
      examTitle: '',
      isOver: false
    };
  },
  props: {
    examid: {
      type: String,
      default: ''
    },
    batchid: {
      type: String,
      default: ''
    },
    stepMode:{
      type:Boolean,
      default:false
    }
  },
  computed: {
    //获取当前路由名称
    type() {
      return this.$route.name;
    },
    modalSelection() {
      const { modalDefaultKey } = this;
      return {
        selectedRowKeys: modalDefaultKey,
        onChange: this.onModalSelectChange
      };
    },
    tableSelection() {
      const { tableDefaultKey } = this;
      return {
        selectedRowKeys: tableDefaultKey,
        onChange: this.onTableSelectChange
      };
    }
  },
  mounted() {
    this.getOpeartion();
  },
  methods: {
    /*************权限判断******************************/
    // 判断是否是只读
    getIsWrite(type) {
      type = 'add/edit/del:monitor';
      let index = this.IsOpList.findIndex((el) => {
        return el.Name === type;
      });
      if (index > -1) {
        if (this.IsOpList[index].IsRead && !this.IsOpList[index].IsWrite) {
          this.$message.info('您没有该操作权限！');
          return false;
        } else {
          return true;
        }
      }
    },
    // 获取页面操作
    getOpeartion() {
      this.loading = true;
      this.GetOperationList('examId',this.examid,'proctorTeacher').then((rst) => {
        this.loading = false;
        this.operationList = [];
        this.IsOpList = [];
        if (rst.code === 1) {
          this.isOver = rst.isOver;
          if (rst.list.length) {
            rst.list.forEach((item) => {
              if (item.IsWrite) {
                this.operationList.push(item.Name);
              }
              this.IsOpList = rst.list;
            });
          }
          this.getTeacherListForType();
          this.examTitle = rst.examTitle;
          this.batchTitle = rst.batchTitle;
        } else {
          this.$message.error(rst.msg);
        }
      });
    },

    /***************************获取教师列表***************************************** */
    //获取已添加老师列表
    getTeacherListForType() {
        this.getProctorTeacherList();
        if (this.columns.length == 8) {
          this.columns.splice(5, 1);
        }
    },
    //获取监考老师列表
    getProctorTeacherList(current, pageSize, sort) {
      var that = this;
      this.getType = 0;
      this.loading = true;
      this.$http
        .post('/api/examMonitor/ExamMonitor/getMonitorTeaList', {
          getType: this.getType,
          examId: this.examid,
          sort: '',
          key: this.searchName,
          schoolName: '',
          page: current || 1,
          pageSize: pageSize || 10
        })
        .then((rst) => {
          this.loading = false
          if (rst.code > 0) {
            this.dataList = [];
            this.tablePagination.current = rst.pagination.pageIndex;
            this.tablePagination.pageSize = rst.pagination.pageSize;
            this.tablePagination.total = rst.pagination.totalCount;
            this.searchName = '';

            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                this.dataList.push({
                  ...item,
                  key: item.Id,
                  number: number
                });
              });
            }
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },
    // 点击table分页，排序
    onTableChange(pagenation, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
        this.getProctorTeacherList(pagenation.current, pagenation.pageSize, sortOrder);
    },
    //查询教师
    searchTeacherForType() {
        this.getProctorTeacherList();
    },
    /**************************获取待添加教师列表****************************** */
    //获取待添加的教师列表
    getAddTeacherListForType() {
      // debugger;
      if (!this.getIsWrite('导入教师')) {
        return;
      }
        this.getAddProctorTeacherList();
        this.importTeacherModal = true;
    },
    distributionStu() {
      if(!this.isOver){
        this.distribution(0);
      }else{
        this.cancelPublish = true;
      }
    },
    //一键分配考生
    distribution(examType) {
      this.$http
        .post('/api/examMonitor/ExamMonitor/distributionStu', {
          examType: examType,
          examId: this.examid
        })
        .then((rst) => {
          if (rst.code > 0) {
            this.cancelPublish = false;
            this.$message.success(rst.msg);
            this.getProctorTeacherList();
          } else {
            this.$message.warning(rst.msg);
          }
        });
    },
    //获取待添加监考老师列表
    getAddProctorTeacherList(current, pageSize, sort) {
      // debugger;
      var that = this;
      this.getType = 1;
      this.loading = true;
      this.$http
        .post('/api/examMonitor/ExamMonitor/getMonitorTeaList', {
          getType: this.getType,
          examId: this.examid,
          key: this.searchName,
          schoolName: '',
          page: current || 1,
          pageSize: pageSize || 10
        })
        .then((rst) => {
          this.loading = false
          if (rst.code > 0) {
            this.importDataList = [];
            this.modalPagination.current = rst.pagination.pageIndex;
            this.modalPagination.pageSize = rst.pagination.pageSize;
            this.modalPagination.total = rst.pagination.totalCount;
            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                this.importDataList.push({
                  ...item,
                  key: item.Id,
                  number: number
                });
              });
            }
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },
    // 点击modal分页，排序
    onModalChange(pagenation, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
        this.getAddProctorTeacherList(pagenation.current, pagenation.pageSize, sortOrder);
    },
    // 获取modal选择的
    onModalSelectChange(selectedRowKeys, selectedRow) {
      this.modalDefaultKey = selectedRowKeys;
    },
    //添加监考教师
    addProctorTeacher() {
      if (!this.modalDefaultKey.length) {
        this.$message.warning(`请选择要添加的教师`);
        return;
      }
      this.loading = true;
      var that = this;
      this.$http
        .post('/api/examMonitor/ExamMonitor/addMarkTea', {
          ids: this.modalDefaultKey,
          examId: this.examid
        })
        .then((rst) => {
          this.loading = false
          if (rst.code > 0) {
            that.$message.success(rst.msg);
            that.getTeacherListForType();
            that.importedCancel();
            that.stepMode && that.$parent.getExamStatus(2)
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },
    /**************************删除教师****************************** */
    //批量删除数据
    deleteBatchTeacherForType() {
      if (!this.getIsWrite('删除')) {
        return;
      }
        this.deleteBatchProctorTeacher();
    },
    //批量删除监考老师
    deleteBatchProctorTeacher() {
      if (!this.tableDefaultKey.length) {
        this.$message.warning(`请选择要删除的教师`);
        return;
      }
      this.loading = true;
      this.deleteProctorTeacher(this.tableDefaultKey);
    },
    //单个删除数据
    deleteTeacherForType(id) {
      if (!this.getIsWrite('删除')) {
        return;
      }
        this.deleteProctorTeacher(id);
    },
    // 点击操作
    clickAction(record) {
      this.choiceTeaId = record;
      if (!this.isOver) {
        this.choicePaper(0);
      } else {
        this.choice = true;
      }
    },
    choicePaper(examType) {
      if (this.choiceTeaId == '') {
        that.$message.warning('请选择监考教师');
        return;
      }
      this.choice = false;
      this.$router.push({
        name: this.$route.name === 'proctorTeacher' ? 'examMonitorStu' : 'examMonitorStuOne',
        params: {
          examid: this.examid,
          teacherid: this.choiceTeaId.TeacherId,
          teacherkey: this.choiceTeaId.UserNo, //工号
          examType: examType
        }
      });
    },
    //删除监考老师
    deleteProctorTeacher(id) {
      var that = this;
      this.loading = true;
      this.$http
        .post('/api/examMonitor/ExamMonitor/deleteTea', {
          ids: id,
          examId: this.examid
        })
        .then((rst) => {
          this.loading = false
          if (rst.code > 0) {
            this.getTeacherListForType();
            this.displayCancel();
            that.$message.success(rst.msg);
            that.stepMode && that.$parent.getExamStatus(2)
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },

    //获取table选择数据
    onTableSelectChange(selectedRowKeys, selectedRow) {
      this.tableDefaultKey = selectedRowKeys;
    },

    importedCancel() {
      this.importTeacherModal = false;
      this.searchName = '';
      this.modalDefaultKey = [];
      this.tableDefaultKey = [];
      this.selectModalValue = [];
    },
    // 重置状态
    displayCancel() {
      this.searchName = '';
      this.modalDefaultKey = [];
      this.tableDefaultKey = [];
    }
  }
};
</script>
